package com.bowen.spike.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.bowen.spike.context.UserContext;
import com.bowen.spike.entity.User;
import com.bowen.spike.mapper.UserMapper;
import com.bowen.spike.my_enum.Gender;
import com.bowen.spike.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bowen.spike.util.JwtUtil;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author bowen
 * @since 2025-04-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public String login(User user) {
         // 查询用户和密码
        user = lambdaQuery()
                .eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, SecureUtil.md5(user.getPassword()))
                .one();

        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        //查询成功，返回jwt令牌
        return JwtUtil.getToken(user.getId());
    }

    @Override
    public void register(User user) {
        try {
            user.setPassword(SecureUtil.md5(user.getPassword())); //md5 加密
            save(user);
        } catch (Exception e) {
            throw new RuntimeException("用户名已经存在", e);
        }
    }

    @Override
    public void changePassword(String password) {
        Long loginUserId = UserContext.getUserId();
        lambdaUpdate()
                .eq(User::getId, loginUserId)
                .set(User::getPassword, password)
                .update();
    }

    @Override
    public void changeGender(Gender gender) {
        Long loginUserId = UserContext.getUserId();
        lambdaUpdate()
                .eq(User::getId, loginUserId)
                .set(User::getGender, gender)
                .update();
    }
}
